package com.tang.subject.application.controller.interceptor;

import com.tang.common.enums.HeaderAndContextNameEnum;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //根据请求上下文获取请求数据
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(requestAttributes)) {
            return;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String loginId = request.getHeader(HeaderAndContextNameEnum.LOGIN_ID.getName());
        if (Objects.isNull(loginId)) {
            return;
        }
        requestTemplate.header(HeaderAndContextNameEnum.LOGIN_ID.getName(), loginId);
    }
}
